package com.xiejr.handler;


import com.xiejr.enumeration.ResultEnum;
import com.xiejr.model.exception.BusinessException;
import com.xiejr.model.vo.ResultVO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: fasttm
 * @description: 全局异常捕获
 * @author: xjr
 * @create: 2020-07-21 15:30
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Map<String, Object> methodDtoNotValidException(Exception ex, HttpServletRequest request) {
        MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
        List<ObjectError> errors = c.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> {

            errorMsg.append(x.getDefaultMessage()).append(";");
        });
        Map<String, Object> respMap = new HashMap<>(4);
        respMap.put("code", -1);
        respMap.put("error", errorMsg);
        return respMap;
    }

    @ExceptionHandler(BusinessException.class)
    public ResultVO EtExceptionHandler(BusinessException ex) {
        ResultEnum resultEnum = ex.getResultEnum();
        ResultVO resultVO = new ResultVO();
        resultVO.setCode(resultEnum.getCode());
        resultVO.setError(ex.getMessage());
        return resultVO;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResultVO duplicateKeyException(DuplicateKeyException ex) {
        return ResultVO.failure("数据库主键冲突,请检查请求参数");
    }

    @ExceptionHandler(Exception.class)
    public ResultVO unknownException(Exception ex) {
        return ResultVO.failure("业务异常,具体原因" + ex.getMessage());
    }


}
